// processor definitions
//#include "inc/lm4f120h5qr.h"


#include "inc/hw_ints.h"
#include "inc/hw_memmap.h"
#include "inc/hw_types.h"
#include "driverlib/sysctl.h"
#include "driverlib/interrupt.h"
#include "driverlib/gpio.h"
#include "driverlib/timer.h"
#include "inc/hw_gpio.h"
#include "inc/hw_sysctl.h"
#include "driverlib/rom.h"


#define PD_0 GPIO_PIN_0	//0x00000001
#define PD_1 GPIO_PIN_1	//0x00000002
#define PD_2 GPIO_PIN_2	//0x00000004
#define PD_3 GPIO_PIN_3	//0x00000008
#define PD_4 GPIO_PIN_4	//0x00000010
#define PD_5 GPIO_PIN_5	//0x00000020
#define PD_6 GPIO_PIN_6	//0x00000040
#define PD_7 GPIO_PIN_7	//0x00000080

#define redled GPIO_PIN_1


int delay(int time);
unsigned long ulPeriod;
int count = 0;
int flip = 0;

int main(void) {

	//enable clock, 200MHz/5 = 40MHz
	ROM_SysCtlClockSet(SYSCTL_SYSDIV_5 | SYSCTL_USE_PLL | SYSCTL_XTAL_16MHZ | SYSCTL_OSC_MAIN);

	// enable PORT D GPIO peripheral
	ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOD | SYSCTL_PERIPH_GPIOF);

	// set LED PORT D pins as outputs
	ROM_GPIOPinTypeGPIOOutput(GPIO_PORTD_BASE, (PD_0 | PD_1 | PD_2 | PD_3 | PD_4 | PD_5 | PD_6 | PD_7));
	ROM_GPIOPinTypeGPIOOutput(GPIO_PORTF_BASE, redled);

	ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_TIMER0);
	ROM_TimerConfigure(TIMER0_BASE, TIMER_CFG_PERIODIC);

	//set timer period: 40MHz/10/2 = 2MHz = 0.5us
	//for 1000us = 1ms use Div by 0.1 and then 4, 40MHz / 0.1 / 4 = 1ms
	ulPeriod = (ROM_SysCtlClockGet());		//for 1ms
	ROM_TimerLoadSet(TIMER0_BASE, TIMER_A, ulPeriod - 1);

	ROM_TimerIntClear(TIMER0_BASE, TIMER_TIMA_TIMEOUT);

	ROM_IntEnable(TIMER_A);
	ROM_TimerIntEnable(TIMER0_BASE, TIMER_TIMA_TIMEOUT);
	ROM_IntMasterEnable();
	
	ROM_TimerEnable(TIMER0_BASE, TIMER_A);

	//init pins
	ROM_GPIOPinWrite(GPIO_PORTD_BASE, 0x000000ff, 0);
	ROM_GPIOPinWrite(GPIO_PORTF_BASE, redled, 0);
	

	// loop forever
	while(1);
}

void Timer0IntHandler(void)
{
	//clear interrupt
	ROM_TimerIntClear(TIMER0_BASE, TIMER_TIMA_TIMEOUT);

	if(!flip) count++;
	else count--;

	count = count%7;	

	if(count == 0) {
		flip = flip ^ 0xff;
		count = 7;
	}

	//do led shifting here
	ROM_GPIOPinWrite(GPIO_PORTD_BASE, 0x000000ff, (PD_0<<count));


	//reset counter value back to 10000
	ROM_TimerLoadSet(TIMER0_BASE, TIMER_A, ulPeriod);


	//test
	ROM_GPIOPinWrite(GPIO_PORTF_BASE, redled, flip);
}
